package com.swipemaster.network;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;

import android.content.Context;

import com.swipemaster.common.Global;
import com.swipemaster.common.Prefs;

public class Security
{
	private final static String PRIVATE_KEY = "&*?@$HFWasw4262.!yo";
	private final static String ALGORITHM = "SHA-1";
	private static long userId;

	public static String getHash(String... args)
	{
		final StringBuilder argument = new StringBuilder();
		for (final String arg : args)
		{
			argument.append(arg);
		}
		argument.append(PRIVATE_KEY);

		byte[] hash = null;
		try
		{
			final MessageDigest messageDigest = MessageDigest.getInstance(ALGORITHM);
			hash = messageDigest.digest(argument.toString().getBytes());
		}
		catch (final NoSuchAlgorithmException e)
		{
			e.printStackTrace();
		}

		return byteArray2HexString(hash);
	}

	public static long getUserId()
	{
		return userId;
	}

	public static void setUserId(Context context)
	{
		userId = Global.app.prefs.getLong(Prefs.USER_ID_KEY, 0);
		if (userId == 0)
		{
			userId = System.currentTimeMillis();
			Global.app.prefs.putObject(Prefs.USER_ID_KEY, userId);
		}
	}

	private static String byteArray2HexString(byte[] hash)
	{
		final Formatter formatter = new Formatter();
		for (final byte b : hash)
		{
			formatter.format("%02x", b);
		}
		return formatter.toString();
	}
}
